package com.github.elliot.usercenter.config;

import org.springframework.data.domain.Page;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.relational.core.query.Query;
import reactor.core.publisher.Mono;

public class R2dbcPageAgent<T> {

    private Class<T> entityClass;

    private R2dbcEntityTemplate r2dbcEntityTemplate;

    public R2dbcPageAgent(R2dbcEntityTemplate r2dbcEntityTemplate, Class<T> entityClass) {
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
        this.entityClass = entityClass;
    }

    public Mono<Page<T>> findPageByQuery(Query query, int page, int size) {
        Pageable pageable=PageRequest.of(page-1, size);
        return r2dbcEntityTemplate.select(query.with(pageable), entityClass).collectList()
                .flatMap(r -> {
                    return r2dbcEntityTemplate.count(query, entityClass).map(count -> {
                        return new PageImpl<>(r, pageable, count);
                    });
                });
    }

    public Mono<Page<T>> findPage(int page,int size) {
        return findPageByQuery(null, page,size);
    }
}
